package com.das.mechanic_base.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.main.X3AppearanceRecognitionStausAdapter;
import com.das.mechanic_base.adapter.main.X3CameraDetectionNewAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.alone.AloneCarBean;
import com.das.mechanic_base.bean.alone.AloneImageAndRecordBean;
import com.das.mechanic_base.bean.alone.DashboardWarnBean;
import com.das.mechanic_base.bean.alone.PictureRecogintionResultBean;
import com.das.mechanic_base.bean.alone.PictureRecognitionBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.def.alone.AloneUploadStatus;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.mvp.view.camera.X3CameraPhotoActivity;
import com.das.mechanic_base.utils.X3AloneLayoutUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class X3AppearanceamageDialog extends X3BaseBottomSheetDialog implements X3CameraDetectionNewAdapter.IOnItemCameraClick, View.OnClickListener, X3EditAppearanceamageDialog.IOnRefresh {

    private X3AloneLayoutUtils layoutUtils;
    private long receiveBaseId;
    private long carId;
    private LinearLayout ll_content;
    private String cameraSn;
    private RecyclerView recyclerview;
    private HashMap<String, AloneCarBean> cameraAllList;
    private LinearLayout ll_clear;
    private String questionToSystemSn;
    private X3AppearanceRecognitionStausAdapter appearanceRecognitionStausAdapter;
    private X3CameraDetectionNewAdapter cameraDetectionNewAdapter;
    private List<String> pList;
    private LinearLayout ll_result;
    private TextView tv_result;
    private X3EditAppearanceamageDialog editAppearanceamageDialog;
    private int from ;
    private boolean isSuccessAppearance=true;
    private boolean isshow=false;//控制识别失败的弹窗是否显示
    private Handler handler =new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

            if (!X3StringUtils.isEmpty(questionToSystemSn)) {//外观损伤
                getrecognitionStatus(questionToSystemSn, receiveBaseId);
            }
            handler.postDelayed(this, 1000);
        }
    };
    private ImageView iv_loading;
    private List<AloneImageAndRecordBean> imageList;
    private LinearLayout ll_top;
    private TextView tv_title;
    private String title;
    private LinearLayout ll_loading;

    public X3AppearanceamageDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
//        String token = (String) SpHelper.getData("token", "");
//        System.out.println("当前token"+token);
        tv_title = findViewById(R.id.tv_title);
        tv_title.setText(title);
        layoutUtils = new X3AloneLayoutUtils(mContext);
        ll_content = findViewById(R.id.ll_content);
        ll_clear = findViewById(R.id.ll_clear);
        ll_result = findViewById(R.id.ll_result);
        tv_result = findViewById(R.id.tv_result);
        ll_clear.setOnClickListener(this);
        recyclerview=findViewById(R.id.recyclerview);
        TextView tv_edit = findViewById(R.id.tv_edit);
        tv_edit.setOnClickListener(this);
        Button btn_next = findViewById(R.id.btn_next);
        btn_next.setOnClickListener(this);
        iv_loading = findViewById(R.id.iv_loading);
        ll_loading = findViewById(R.id.ll_loading);
        ll_top = findViewById(R.id.ll_top);
        LinearLayoutManager linearLayoutManager= new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        recyclerview.setLayoutManager(linearLayoutManager);
        appearanceRecognitionStausAdapter = new X3AppearanceRecognitionStausAdapter(mContext);
        recyclerview.setAdapter(appearanceRecognitionStausAdapter);

    }
    public void setDialogTitle(String title){
        this.title=title;
    }
    /*
     *网页跳转0  原生页面跳转1
     * */
    public void from(int from){
        this.from=from;
        System.out.println("来自"+from);
        if(from == 0){
            handler.postDelayed(runnable, 1000);
        }

    }

    public void setDetailSystemSn(String questionToSystemSn,  long receiveBaseId,long carId) {
        this.receiveBaseId = receiveBaseId;
        this.carId = carId;
        this.questionToSystemSn = questionToSystemSn;
        NetWorkHttp.getApi().getDetailBySystemSn(questionToSystemSn, receiveBaseId)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<DashboardWarnBean>() {
                    @Override
                    protected void onDone(DashboardWarnBean dashboardWarnBean) {
                        if (dashboardWarnBean!=null) {
                            showTyreView(dashboardWarnBean,questionToSystemSn);
                        }

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    private void showTyreView(DashboardWarnBean dashboardWarnBean, String questionToSystemSn) {
        //识别结果
//        iv_loading.setVisibility(View.GONE);
        ll_loading.setVisibility(View.GONE);
        if(dashboardWarnBean.failResourceIdList != null && dashboardWarnBean.failResourceIdList.size()>0){//失败图片集合
            ll_top.setVisibility(View.VISIBLE);
        }else {
            ll_top.setVisibility(View.GONE);
        }
        if(dashboardWarnBean.recognitionList != null&&dashboardWarnBean.recognitionList.size() > 0) {

            List<DashboardWarnBean.RecognitionResult> recognitionList = dashboardWarnBean.recognitionList;
            ll_result.setVisibility(View.VISIBLE);
            tv_result.setVisibility(View.VISIBLE);
            recyclerview.setVisibility(View.VISIBLE);
            //tv_result.setText(mContext.getString(R.string.manual_edit_resultg)+recognitionList.size()+mContext.getString(R.string.manual_edit_results)+"");
            tv_result.setText(String.format(mContext.getString(R.string.x3_manual_edit_result),recognitionList.size()));
            appearanceRecognitionStausAdapter.setList(recognitionList);

        }else {

            ll_result.setVisibility(View.GONE);
            tv_result.setVisibility(View.GONE);
            recyclerview.setVisibility(View.GONE);

        }

        List<DashboardWarnBean.ReSourceUrl> resourceUrlList = dashboardWarnBean.resourceUrlList;
        if (X3StringUtils.isListEmpty(resourceUrlList)) {

            resourceUrlList = new ArrayList<>();
        }
//        if (cameraDetectionNewAdapter != null && resourceUrlList.size() == cameraDetectionNewAdapter.getImgList().size()) {
//            return;
//        }

        ll_content.removeAllViews();
        cameraAllList = new HashMap<>();
        X3MyRecyclerview photoRecy = layoutUtils.getDetectionRecyclerview();
        imageList = new ArrayList<>();
        if (!X3StringUtils.isListEmpty(resourceUrlList)) {
            for(int i = 0 ; i < resourceUrlList.size(); i++){
                AloneImageAndRecordBean imageAndRecordBean = new AloneImageAndRecordBean(resourceUrlList.get(i).value,resourceUrlList.get(i).value, resourceUrlList.get(i).key, AloneUploadStatus.UPLOADING_SUCCESS);
                imageAndRecordBean.failStatus = resourceUrlList.get(i).failStatus;
                imageList.add(imageAndRecordBean);
            }
        }

        cameraDetectionNewAdapter = new X3CameraDetectionNewAdapter(mContext, true,questionToSystemSn);
        photoRecy.setAdapter(cameraDetectionNewAdapter);
        cameraDetectionNewAdapter.changeData(imageList);
        cameraDetectionNewAdapter.setiOnItemCameraClick(this);
        cameraAllList.put(questionToSystemSn,new AloneCarBean(photoRecy, cameraDetectionNewAdapter));
        ll_content.addView(photoRecy);

        if(X3StringUtils.isListEmpty(dashboardWarnBean.resourceUrlList) && X3StringUtils.isListEmpty(dashboardWarnBean.elements) && X3StringUtils.isListEmpty(dashboardWarnBean.recognitionList)){
            //数据为空  直接跳转 拍照页面
            takeCamrea(questionToSystemSn);
        }
    }


    @Override
    public void show() {
        super.show();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
    @Override
    protected int getLayoutId() {
        return R.layout.x3_dialog_appearancedamage;
    }

    @Override
    public void iOnItemCameraClick(String sn) {
        takeCamrea(sn);
    }

    @Override
    public void iOnDeleteClick(long resId, int position, String sn, String path) {
//        saveOrUpdateWorkResource(resId,sn,false,path);

        if(resId == 0){//上传失败的
            return;
        }
        isshow = false;
        NetWorkHttp.getApi().deletePicture(resId)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<String>() {
                    @Override
                    protected void onDone(String data) {
                        System.out.println("删除成功了");
                        if(cameraDetectionNewAdapter !=null ){//控制识别失败的弹窗是否显示
                            if(imageList!=null && imageList.size() > 0) {
                                imageList.remove(position);
                                System.out.println("已删除后的集合"+imageList.toString());
                                for (int i = 0; i < imageList.size(); i++) {
                                    if (imageList.get(i).failStatus) {//识别失败的图片
                                        isshow = true;
                                    }
                                }
                                System.out.println("已删除后"+ isshow);
                                if (isshow) {
                                    isshow=false;
                                    ll_top.setVisibility(View.VISIBLE);
                                } else {
                                    isshow=true;
                                    ll_top.setVisibility(View.GONE);
                                }
                            } else {
                                isshow=true;
                                ll_top.setVisibility(View.GONE);
                            }


                        }

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        System.out.println("删除失败了");
                    }
                });


    }

    @Override
    public void iOnAgainUploadImage(String path, String sn, int imageIndex) {
        uploadImageAws(new File(path),sn,false);
    }
    /**
     * 从相册中选取图片 或者拍照 数据都会从这个方法进入
     * @param cameraBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetPictureOrVideo(CameraBean cameraBean) {
        if (cameraBean == null) {
            return;
        }
        switch ((int) cameraBean.resultCode) {
            //图片或者视频
            case X3Constent.CODE_CAMERA_REQUEST:
            case X3Constent.CODE_GALLERY_REQUEST:
                if (cameraBean.cameraData == null) {
                    return;
                }
                pList = (List<String>) cameraBean.cameraData;
                System.out.println("接收到的数据"+pList.size());
//                iv_loading.setVisibility(View.VISIBLE);
                ll_loading.setVisibility(View.VISIBLE);
                count = 0;
//                Glide.with(mContext).load(R.drawable.skeletongloading)
//                        .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true))
//                        .into(iv_loading);
                for (String path : pList) {
                    if (!X3StringUtils.isEmpty(path)) {
                        cameraAllList.get(cameraSn).getDetectionNewAdapter().addData(new AloneImageAndRecordBean(path,"",0,AloneUploadStatus.UPLODING));

                        new Handler().postDelayed(() -> {
                            uploadImageAws(new File(path),cameraSn,false);
                        },200);

                    }
                }
                EventBus.getDefault().post("REFRESHAPPEARANCE");
                Log.e("开始传2","上传：");
                break;
            default:
                break;
        }
    }
    private  int  count=0;
    private void uploadImageAws(File imgFile,String sn,boolean isSound) {
        if (!imgFile.exists()) {
            return;
        }

        RequestBody requestBody;
        if (imgFile.getPath().endsWith(".mp4") || imgFile.getPath().endsWith(".mov")) {
            requestBody = RequestBody.create(MediaType.parse("video/mp4"), imgFile);
        }else {
            requestBody = RequestBody.create(MediaType.parse("image/jpg"), imgFile);
        }
        try {
            String  filename = URLEncoder.encode(imgFile.getName(), "UTF-8");
            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            Map<String,RequestBody> map = new HashMap<>();

            map.put("description",RequestBody.create(MediaType.parse("multipart/form-data"), "检测图片"));

            map.put("ossBucketName",RequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));

            NetWorkHttp.getApi().getDetectionPictureRecognition(carId,fileBody,sn,receiveBaseId)//初检车辆图片识别
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(((X3IBaseView)mContext).bindToLife())
                    .subscribe(new HttpCallBack<PictureRecognitionBean>() {
                        @Override
                        protected void onDone(PictureRecognitionBean awsFileBean) {
                            Log.e("开始传1","上传：");
                            saveOrUpdateWorkResource(awsFileBean.id,sn,true,imgFile.getPath());
                            count++;
                            if(pList != null && pList.size() > 0 && count == pList.size()){//多次上传 完毕
                                Log.e("上传完毕","上传："+count);
                                //定时器 初检车辆图片识别状态查询
                                X3BottomHomeAloneCarDialog.isSuccessAppearance=true;
                                isSuccessAppearance=true;


                            }

                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {
                            saveOrUpdateWorkResource(0,sn,true,imgFile.getPath());
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    /**
     * 更新精检图片
     * @param resId
     * @param sn
     */
    public void saveOrUpdateWorkResource(long resId,String sn,boolean isUpload,String path) {
        /**
         * 如果resId == 0 说明上传失败直接回调
         */
        getUpdatePictureSuccess(new AloneImageAndRecordBean(path,path,resId, resId == 0 ? AloneUploadStatus.UPLOADING_FAILED : AloneUploadStatus.UPLOADING_SUCCESS),sn,isUpload);
    }
    /**
     * 更新图片成功
     * @param aloneImageAndRecordBean
     * @param sn
     * isUpload 是否是上传图片  false为删除图片
     */
    public void getUpdatePictureSuccess(AloneImageAndRecordBean aloneImageAndRecordBean, String sn,boolean isUpload) {
        if (aloneImageAndRecordBean == null) {
            return;
        }
        List<AloneImageAndRecordBean> cameraList = cameraAllList.get(sn).getDetectionNewAdapter().getImgList();
        if (X3StringUtils.isListEmpty(cameraList)) {
            return;
        }
        int refreshIndex = -1;
        String currentPath = aloneImageAndRecordBean.getPath();
        for (int i = 0; i < cameraList.size(); i++) {
            String path = cameraList.get(i).getPath();

            long uploadStatus = cameraList.get(i).getUploadStatus();
            if (X3StringUtils.isEmpty(path)) {
                continue;
            }
            if (isUpload) {
                if (!X3StringUtils.isEmpty(currentPath) && currentPath.equals(path)
                        && (uploadStatus == AloneUploadStatus.UPLODING || uploadStatus == AloneUploadStatus.UPLOADING_FAILED)) {
                    refreshIndex = i;
                    break;
                }
            }else {
                if (!X3StringUtils.isEmpty(currentPath) && currentPath.equals(path)) {
                    refreshIndex = i;
                    break;
                }
            }

        }
        if (refreshIndex == -1) {
            return;
        }

        long uploadStatus = aloneImageAndRecordBean.getUploadStatus();
        int realStatus = ((uploadStatus == AloneUploadStatus.UPLODING || uploadStatus == AloneUploadStatus.UPLOADING_SUCCESS) ? AloneUploadStatus.UPLOADING_SUCCESS : AloneUploadStatus.UPLOADING_FAILED);
        aloneImageAndRecordBean.setUploadStatus(realStatus);
        if (isUpload) {
            cameraAllList.get(sn).getDetectionNewAdapter().changeData(aloneImageAndRecordBean,refreshIndex);

        }else {
            cameraAllList.get(sn).getDetectionNewAdapter().deleteImage(refreshIndex);
        }

    }

    @Override
    public void dismiss() {
        MobclickAgent.onPageEnd("初检信息外观损伤弹窗");
        EventBus.getDefault().unregister(this);
            if (iOnRefresh != null) {
                iOnRefresh.iOnRefreshData();
            }
            if(handler!=null){
                handler.removeCallbacks(runnable);
                handler = null;
            }
        super.dismiss();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_clear) {
            NetWorkHttp.getApi().deleteDetectionFirstBySystemSn(questionToSystemSn, receiveBaseId)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(((X3IBaseView) mContext).bindToLife())
                    .subscribe(new HttpCallBack<String>() {
                        @Override
                        protected void onDone(String data) {
                            System.out.println("清空的请求成功了");
                            if (cameraDetectionNewAdapter == null) {
                                return;
                            }

                            List<AloneImageAndRecordBean> imageList = new ArrayList<>();
                            imageList.clear();
                            cameraDetectionNewAdapter.changeData(imageList);

                            if (appearanceRecognitionStausAdapter == null) {
                                return;
                            }

                            ArrayList<DashboardWarnBean.RecognitionResult> listelements = new ArrayList<>();
                            listelements.clear();
                            appearanceRecognitionStausAdapter.setList(listelements);
                            ll_result.setVisibility(View.GONE);
                            tv_result.setVisibility(View.GONE);
                            recyclerview.setVisibility(View.GONE);
                            ll_top.setVisibility(View.GONE);
                            //通知初检信息页面刷新接口
                            EventBus.getDefault().post("UPDATE_PRELIMINARY_INSPECTION_INFORMATION");
                            dismiss();
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });
        } else if (id == R.id.btn_next) {
            dismiss();
        } else if (id == R.id.tv_edit) {//编辑车损
            // if (editAppearanceamageDialog == null) {
            editAppearanceamageDialog = new X3EditAppearanceamageDialog(mContext);
            //  }
            editAppearanceamageDialog.show();
            editAppearanceamageDialog.setQuestionSystemSn(questionToSystemSn, receiveBaseId);
            editAppearanceamageDialog.setiOnRefresh(this);
        }
    }

    @Override
    public void iOnRefreshData() {
        setDetailSystemSn(questionToSystemSn,receiveBaseId,carId);
    }

    /*
     *初检车辆图片识别状态查询
     */
    public void getrecognitionStatus(String appearancequestionToSystemSn,long receiveBaseId) {
        this.receiveBaseId = receiveBaseId;
        NetWorkHttp.getApi().getrecognitionStatus(questionToSystemSn,receiveBaseId)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<PictureRecogintionResultBean>() {
                    @Override
                    protected void onDone(PictureRecogintionResultBean pictureRecogintionResultBean) {
                        System.out.println("初检车辆图片识别状态查询");
                        if (pictureRecogintionResultBean == null) {
                            return;
                        }

                        long finishAmount = pictureRecogintionResultBean.finishAmount;
                        long totalAmount = pictureRecogintionResultBean.totalAmount;

                        if (totalAmount < 0) {
                            return;
                        }

                        if (totalAmount == 0) {
                            return;
                        }

                        if(questionToSystemSn == appearancequestionToSystemSn && finishAmount != totalAmount) {//外观损伤
                            isSuccessAppearance=true;
                            System.out.println("车损外观数据不相等");
                        }
                        if ( questionToSystemSn == appearancequestionToSystemSn && finishAmount == totalAmount && isSuccessAppearance) {
                            isSuccessAppearance=false;
                            // 完成
                            System.out.println("车损外观数据相等");
                            setDetailSystemSn(appearancequestionToSystemSn,receiveBaseId,carId);
                            return;
                        }

                        //totalAmount>0   finishAmount!=totalAmount 请求中
                        //totalAmount>0  totalAmount ==finishAmount   完成



                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }
    /**
     * 刷新数据
     */
    public interface IOnRefresh {
        void iOnRefreshData();
    }
    IOnRefresh iOnRefresh;

    public void setiOnRefresh(IOnRefresh iOnRefresh) {
        this.iOnRefresh = iOnRefresh;
    }

    private  void  takeCamrea(String sn){
        XXPermissions.with((Activity) mContext)
                .permission(Permission.CAMERA)
                .permission(Permission.RECORD_AUDIO)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            cameraSn = sn;
                            // 当前已经拍摄的照片或者视频的数量
                            int size = cameraAllList.get(cameraSn).getDetectionNewAdapter().getCameraList().size();
                            if (9 - size == 0) {
                                X3ToastUtils.showMessage(mContext.getString(R.string.x3_upload_mast_nine));
                                return;
                            }
                            // TODO 跳转到拍照页面
                            //changeRlCamera(View.VISIBLE);

                            Intent intent = new Intent(mContext, X3CameraPhotoActivity.class);
                            intent.putExtra("allNum",9 - size);
                            intent.putExtra("isAlbum",4);//4 外观损伤
                            mContext.startActivity(intent);
                            ((Activity)mContext).overridePendingTransition(R.anim.activity_enter, 0);
                        }else {
                            X3ToastUtils.showMessage(mContext.getString(R.string.x3_camera_permiss) + "");
                            XXPermissions.startPermissionActivity(mContext,permissions);
                        }
                    }
                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        X3ToastUtils.showMessage(mContext.getString(R.string.x3_camera_permiss) + "");
                        XXPermissions.startPermissionActivity(mContext,permissions);
                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("初检信息外观损伤弹窗");
    }
}